import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'
// 请求拦截器
http.intercept.request = function (options) {
  const defaultHeader = {}
  defaultHeader.Authorization = `Bearer ${getApp().token}`

  options.header = Object.assign({}, defaultHeader, options.header)

  return options
}

// 响应拦截器
http.intercept.response = async function ({ data, config }) {
  //  判断token 过期
  if (data.code === 401) {
    const app = getApp()
    if (config.url.includes('/refreshToken')) {
      // 页面栈
      const pageStack = getCurrentPages()
      // 获取最后一个页面栈
      const currentPage = pageStack.pop()
      // 获取最后一个页面栈中的页面地址
      const redirectURL = currentPage.route
      // 跳往登录页，带上登录之后跳回去的地址
      return wx.redirectTo({
        url: '/pages/login/index?returnURL=/' + redirectURL,
      })
    }
    const { data, code } = await wx.http({
      url: '/refreshToken',
      method: 'POST',
      header: { Authorization: 'Bearer ' + app.refreshToken },
    })
    if (code !== 10000) {
      return wx.utils.toast('登录状态失效，请重新登录')
    }
    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)
    console.log(config)
    config.header = Object.assign(config.header, {
      Authorization: 'Bearer ' + data.token,
    })
    return http(config)
  }
  return data
}
// 全局对象方式导出
wx.http = http
